package com.ruoyi.project.tool.mtcnn;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class PythonProcessListener implements ApplicationListener {

    @Autowired
    private final PythonProcessor pythonProcessor;

    public PythonProcessListener(PythonProcessor pythonProcessor) {
        this.pythonProcessor = pythonProcessor;
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ContextRefreshedEvent) {
            // Spring应用启动时执行startPythonProcess方法
            try {
                log.info("starting process...");
                pythonProcessor.startPythonProcess();
                log.info("start process success!");
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (event instanceof ContextClosedEvent) {
            // Spring应用关闭时执行closePythonProcess方法
            log.info("closing process...");
            pythonProcessor.closePythonProcess();
            log.info("process has closed!");
        }
    }
}
